//
//  MBDMyIntegrationViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/5.
//

import Foundation
import UIKit
import YYText
import SnapKit
import Toast_Swift

class MBDMyIntegrationViewController : MBDBaseViewController {
    
    var tableView : UITableView!
    var priceDetailLabel : YYLabel!
    
    var viewModel : MBDMyIntegrationViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的积分"
        self.viewModel = MBDMyIntegrationViewModel()

        let rightItem = UIButton(frame: CGRectMake(0, 0, 45, 25))
        rightItem.setImage(UIImage(named: "ico_info"), for: .normal)
        rightItem.addTarget(self, action: #selector(rightItemPressed), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)

        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.allowsMultipleSelection = false
        tableView.allowsSelectionDuringEditing = false
        tableView.allowsMultipleSelectionDuringEditing = false
        self.view.addSubview(tableView)
        
        let headerView = UIView(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, 100))
        headerView.setDynamicForgroundColor()
        priceDetailLabel = YYLabel()
        priceDetailLabel.text = "2"
        priceDetailLabel.textColor = UIColor(colorHex: 0x4273d0)
        priceDetailLabel.font = UIFont.boldSystemFont(ofSize: 66)
        headerView.addSubview(priceDetailLabel)
        priceDetailLabel.snp.makeConstraints { make in
            make.centerY.equalTo(headerView)
            make.left.equalTo(35)
        }
        
        let integrateView = UIImageView()
        integrateView.image = UIImage(named: "ico_integrate_big")
        headerView.addSubview(integrateView)
        integrateView.snp.makeConstraints { make in
            make.centerY.equalTo(priceDetailLabel)
            make.left.equalTo(priceDetailLabel.snp.right).offset(8)
            make.size.equalTo(CGSizeMake(22, 22))
        }
        
        let getIntegrateButton = UIButton()
        headerView.addSubview(getIntegrateButton)
        getIntegrateButton.addTarget(self, action: #selector(getIntegratePressed), for: UIControl.Event.touchUpInside)

        getIntegrateButton.setTitle("赚积分", for: .normal)
        getIntegrateButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        getIntegrateButton.layer.cornerRadius = 18
        getIntegrateButton.clipsToBounds = true
        getIntegrateButton.setBackgroundColor(color: UIColor(colorHex: 0x4273d0), forState: UIControl.State.normal)
        getIntegrateButton.setBackgroundColor(color: UIColor(colorHex: 0x0951c6), forState: UIControl.State.highlighted)
        getIntegrateButton.setBackgroundColor(color: UIColor.gray, forState: UIControl.State.disabled)
        getIntegrateButton.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(80, 36))
            make.centerY.equalTo(integrateView)
            make.right.equalTo(headerView).offset(-35)
        }
        
        tableView.tableHeaderView = headerView
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])

        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = 100
        
        tableView.register(MBDMyIntegrationCell.self, forCellReuseIdentifier: "MBDMyIntegrationCell")
        tableView.register(MBDMyIntegrationMoreCell.self, forCellReuseIdentifier: "MBDMyIntegrationMoreCell")
        
        self.view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()

    }
    
    override func updateColors() {
        view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()
        
        // 遍历并更新 cellModels
        var result = Array<Any>()
        if let cellModels = self.viewModel.cellModels {
            for i in 0..<cellModels.count {
                let cellModel = cellModels[i]
                if (cellModel as AnyObject).isKind(of: MBDMyIntegrationCellModel.self) {
                    let realCellModel = cellModel as! MBDMyIntegrationCellModel
                    let intergral = realCellModel.integrationDetail
                    realCellModel.integrationDetail = intergral
                }
                result.append(cellModel)
            }
        }
        self.viewModel.cellModels = result
        
        self.tableView.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.viewModel.doRequest { error,result, totalPage,integrateTotal in
            if nil != error {
                self.view.makeToast(error!.localizedDescription,position: .center)
            } else {
                self.viewModel.cellModels = result
                self.tableView.reloadData()
                self.priceDetailLabel.text = String(integrateTotal)
            }
        }
    }
    
    
    
    @objc func getIntegratePressed() {
        self.navigationController?.pushViewController(MBDEarnIntegrationViewController(), animated: true)
    }
    
    @objc func rightItemPressed(){
        let vc = MBDMyIntegrationRuleViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    deinit {
        // perform the deinitialization
        debugPrint("deinit")
    }
}

extension MBDMyIntegrationViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        if cellModel is MBDMyIntegrationCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDMyIntegrationCell", for: indexPath)
            let realCell = cell as! MBDMyIntegrationCell
            realCell.cellModel = cellModel
            return cell

        } else if cellModel is MBDMyIntegrationMoreCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDMyIntegrationMoreCell", for: indexPath)
            let realCell = cell as! MBDMyIntegrationMoreCell
            realCell.cellModel = cellModel
            return cell

        } else {
            return UITableViewCell()
        }

    }
}

extension MBDMyIntegrationViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDMyIntegrationCommonCellModel
        if true == realCellModel.accessory {
            let vc = MBDIntegrationDetailViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, 44))
        view.setDynamicForgroundColor()
        
        let consumptionLabel = UILabel(frame: CGRectMake(25, 0, 100, 44))
        consumptionLabel.font = UIFont.boldSystemFont(ofSize: 16 )
        consumptionLabel.textColor = UIColor(colorHex: 0x4273d0)
        consumptionLabel.text = "积分收支明细"
        view.addSubview(consumptionLabel)
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDCommonCellModel
        return realCellModel.cellHeight()
    }
}

class MBDMyIntegrationMoreCell: MBDCommonCell {
    var moreLabel:YYLabel!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initialize()
    }
    
    override var cellModel: Any! {
        didSet {
            let cellModel = self.cellModel as! MBDMyIntegrationMoreCellModel
            moreLabel.textLayout = cellModel.textLayout
            self.location = cellModel.location
            self.accessable = cellModel.accessory
        }
    }
    
    
    func initialize() {
        self.contentView.setDynamicForgroundColor()
        self.commonBackgroundView.setDynamicForgroundColor()
        
        moreLabel = YYLabel()
        self.commonBackgroundView.addSubview(moreLabel)
        
        moreLabel.snp.makeConstraints { make in
            make.left.equalTo(MBDMyIntegrationCellModel.consumptionLeftMargin)
            make.centerY.equalTo(self.commonBackgroundView)
        }
    }
}


